<?php

namespace app\controllers;

use Yii;
use yii\base\Exception;
use app\models\ParkSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\Land;
use yii\data\ActiveDataProvider;
use yii\db;
use yii\db\Query;
use yii\db\Command;
use ma;

class MaController extends Controller
{

    public function actionIndex(){
        echo 'Hello World!';
    }


    /**
     * 来自Config.php
     * @return array
     */
    public function getconfig()
    {
        $config = array(
            'insertLandInfo' => 'api/land/add-land-field',
            'insertBlockInfo' => 'api/land/add-sub-land-field',
            'insertMultiBlockEnvInfo' => 'api/land/upload-field-env-args-list',

            'key' => '2f795063d70b43cd979b685831aeeb4c',
            'token' => 'c0acff7e8b2e1486',

            'period' => '7200',
        );
        return $config;

    }


    public function actionAjaxsample()
    {
        /*
             $search=['a','b','c'];
             return \Yii::createObject([
                 'class' => 'yii\web\Response',
                 'format' => \yii\web\Response::FORMAT_JSON,
                 'data' => [
                     'message' => $search,
                     'code' => 100,
                 ],
             ]);
        */


        if (Yii::$app->request->isAjax || true) {
            $data = Yii::$app->request->get();
            $DataSet = ['EquipID' => 1, 'data' => 1.0, 'state' => 'common'];
            $DataSet1 = ['EquipID' => 2, 'data' => 'on', 'state' => 'running'];
            $DataSet2 = ['EquipID' => 3, 'data' => '3', 'state' => 'No response'];
            $search = array('parkID' => '1', 'SendDate' => '2015-1-1', 'DataSet' => [$DataSet, $DataSet1, $DataSet2],
                'Language' => 'json');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            //直接return 得到就是json
            return $search;
        }
    }

    /**
     * 得到xml解析，暂时不做，尽量能用XML解析
     */
    public function actionGetxmltest()
    {
        $request = Yii::$app->request;
        //暂时不做，尽量能用XML解析
        if (false && ($request->isPost || $request->isAjax)) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            //返回还是Json？
            $target = $request->post('xml');
            if (empty($target)) {
                $result = array('error' => '1', 'status' => 'No data!');
                return $result;
            } else {
                $xml_obj = simplexml_load_string($target);
                if (empty($xml_obj)) {
                    $result = array('error' => '2', 'status' => 'XML params error!');
                    return $result;
                }
                print_r($xml_obj);
            }
        } else {
            $name = 'actionGetxmltest';
            echo $name;
            //return $this->render('say', ['message' => $name]);
        }
    }

    static public $error_result=array(
        '20010'=>'Verification failed!',
        '20011'=>'Verification failed!No such key and token',
        '200'=> 'success',
        '-1'=>'error in SQL execute!',
        '4000'=>'No data!',
        '20020'=>'json format error!',
        '20021'=>'json format error! No EquipData.',
        '4001'=>'params error!',
        '4002'=>'params error in EquipData!',
        '4003'=>'no Data in EquipData!',
    );

    /**
     * 全部errorcode
     * @param $errornode
     * @return null
     */
    public static function getErrorCode($errornode){

        if(array_key_exists($errornode,self::$error_result)){
            return self::$error_result[$errornode];
        }else{
            return null;
        }
    }


    //模拟post的json
    private static $json_post_server_test='{ "EquipData" :{     "ParkID": "PNS001",     "SendDate": "2015-1-1",     "EquipData": [         {             "EquipID": 1,             "data": 1,             "state": "1"         },         {             "EquipID": 2,             "data": "0",             "state": "1"         },         {             "EquipID": 3,             "data": "1",             "state": "2"         }     ],     "Language": "json" 	} }';

    /**
     * 模拟post到服务器的action
     * 数据是已经设置好的
     */
    public function actionPost_server_test(){
        $time ='2015-12-2';
        $md5_token=self::getconfig()['token'];
        $head_key=self::getconfig()['key'];
        $head_validate_token=$head_key.$md5_token.$time;
        $head_validate_token=md5($head_validate_token);

        $json_to_post=ma\MAAES::encrypt_with_base64(self::$json_post_server_test,$md5_token);//post的加密json

        $header = array(
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
            'key:' . self::getconfig()['key'],
            'validate-token:' . $head_validate_token,
            'timestamp:' . $time,
            //'json:'.$json_to_post,
            //json参数也可以放在header上,但是注意 header头是有大小限制的
        );

        //注意：post中的数据一定要经过转义
        $poststring=ma\matest::replace_post($json_to_post);
//        echo $poststring;
        $options = array(
            CURLOPT_HEADER => true,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_POSTFIELDS => 'json='.$poststring,
            CURLOPT_POST => true,
        );

        $HTTP_HOST=$_SERVER['HTTP_HOST'];//获取当前域名
        $PHP_SELF=$_SERVER['PHP_SELF'];//获取当前网页地址
        $url='http://'.$HTTP_HOST. $PHP_SELF .'?r=ma/postjsontest';//post的目标地址
        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        //ob_start();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//关闭自动输出
        $resData=curl_exec($ch);//执行并输出
        if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') {//剥离body部分
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($resData, 0, $headerSize);//header信息
            $body = substr($resData, $headerSize);//body信息
            echo $body;
        }else{
            echo $resData;
        }

        curl_close($ch);

        //echo $url.'<br>';
        //echo $json_to_post.'<br>';

    }

    /**
     * 通过key在数据库中寻找token
     * @param $database
     * @param $key
     * @return bool
     */
    public function  get_token_from_database($key){
        if(empty($key)){
            return null;
        }
        $token_database_name='token_server';
        $database=$this->getdatabase();
        $query = new Query;
//        $command=$database->createCommand();
        try {
            $query->select($token_database_name)
                ->from('shbb_park')->where('key_server=:key', array('key' => $key));
            $command = $query->createCommand($database);
            $command = $command->queryAll();
        }catch(Exception $e){
            return null;
        }
        if(empty($command)){
            return null;
        }
        return  $command[0][$token_database_name];

    }
    /**
     * 得到Json解析，插入数据库（SQL语句方式）SQL全部正确才插入否则全部回退。
     *  Post方法String Body抬头是
     *  application/x-www-form-urlencoded; charset=UTF-8
     *  如果错了就返回错误了
     */
    /*
     * Yii2表达提交时报错：yii2 Unable to verify your data submission
     * 遇到这种情况，是因为YII2的防止csrf攻击，你则不能多次提交相同的表单。如果你希望当前可以多次重复提交，可以在当前提交的表单controller中添加
     * public $enableCsrfValidation = false;
     * 可是使用post和header传输数据
     * 这句话即可。
     */
    public function  actionPostjsontest()
    {
//       json例子：详见test.json

        $request = Yii::$app->request;
        $headers = Yii::$app->request->headers;
        $target=$headers->get('json');
        $head_key=$headers->get('key');
        $head_timestamp=$headers->get('timestamp');
        $head_validate_token=$headers->get('validate-token');
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        //TODO 以后需要从数据库中获得
        $md5_token=$this->get_token_from_database($head_key);
//        echo 'md5_token'.$md5_token;
        //$md5_token=self::getconfig()['token'];
        if(empty($md5_token)){
            return $this->returnjsontest('20011',self::getErrorCode('20011'));
        }
        if(! (empty($head_key)||empty($head_timestamp)||empty($head_validate_token)) ){//有没有验证信息
            //使用header时注意header大小不能过大，否则会出现400错误,现在最大是409600
            //LimitRequestLine 409400
            //LimitRequestFieldSize 409400
            //默认均为4096

            //下面是验证机制



            $to_md5=$head_key.$md5_token.$head_timestamp;
            $to_md5=md5($to_md5);
            if(! $head_validate_token==$to_md5){
                goto error_2001;//验证失败
            }

        }else{
            error_2001:
            return $this->returnjsontest('20010',self::getErrorCode('20010'));
        }
        if(!empty($target)){//json 代码在headers上
            goto WithHeaders;
        }
        if ($request->isGet) {
            $name = 'actionGetjsontest';
            echo $name;
        } else if ($request->isPost || $request->isAjax) {

            $target = $request->post('json');
            WithHeaders:

            if (empty($target)) {
                //return $this->returnjsontest('1', 'No data!');
//                $retult_example=array();
//                //按照公司的要求修正


                return ['Retult Example'=>self::$error_result];

            } else {
                //TODO post时的转义问题
                //return  ['result'=>$target] ;
                $target=ma\MAAES::decrypt_with_base64($target,$md5_token);



                $json_obj = json_decode($target, true);
                if(empty($json_obj) || !is_array($json_obj) )//json 格式不正确
                {
                    return $this->returnjsontest('20020', self::getErrorCode('20020'));
                }
                if(!(array_key_exists('EquipData',$json_obj)) ){
                    return $this->returnjsontest('20021', self::getErrorCode('20021'));
                }else{
                    $json_obj=$json_obj['EquipData'];
                }
                if (!(array_key_exists('ParkID', $json_obj) && array_key_exists('SendDate', $json_obj) && array_key_exists('EquipData', $json_obj))) {
                    //没有找到所需要的参数
                    return $this->returnjsontest('4001',self::getErrorCode('4001'));

                }
                $parkID = $json_obj['ParkID'];
                $SendDate = $json_obj['SendDate'];//暂时没有用到
                $DataSet = $json_obj['EquipData'];
                $Sql = array();//待插入SQL数组
                $i = 0;
                $sql_unit = ['ParkID', 'EquipID', 'EquipData', 'EquipState'];//插入数据格式及其顺序
                if (is_array($DataSet)) {//判断是不是数组
                    foreach ($DataSet as $Data_one) {

                        if (!(array_key_exists('EquipID', $Data_one) && array_key_exists('data', $Data_one) && array_key_exists('state', $Data_one))) {
                            //判断数据格式
                            //$result=array('error'=>'2','status'=>'params error in DataSet!');
                            //return $result;
                            return $this->returnjsontest('4002',self::getErrorCode('4002'));
                        }
                        $EquipID = $Data_one['EquipID'];
                        $data = $Data_one['data'];
                        $state = $Data_one['state'];
//                        switch ($state) {//状态表以后还会有新的根据数据库和协议进行选择
//                            case 'common':
//                            case 'running':
//                                $state = '1';
//                                break;
//                            case 'no response':
//                            case 'offline':
//                                $state = '2';
//                                break;
//                            case 'warning':
//                                $state = '3';
//                                break;
//                            default :
//                                $state = '1';
//                                break;
//                        }
//                      $Sql=$state;
//                         $Sql[$i]=' insert into `shbbparkrealtimedatatable` (`ParkID`,`EquipID`,`EquipData`,`EquipState`) VALUES ('.
//                             '\''.$parkID.'\''.' , '.'\''.$EquipID.'\''.' , '.'\''.$data.'\''.' , '.'\''.$state.'\''.') ;';
                        $sql_temp = array();//这是每一组数据形成数组。
                        //['ParkID','EquipID','EquipData','EquipState'];顺序
                        $sql_temp[] = $parkID;
                        $sql_temp[] = $EquipID;
                        $sql_temp[] = $data;
                        $sql_temp[] = $state;
                        $Sql[$i] = $sql_temp;
                        $i++;

                    }//end foreach($DataSet as $Data_one)
                    //使用cofig中填写好的新数据库
                    $database=$this->getdatabase();
                    $transaction = $database->beginTransaction();//commit或rollback用
                    try {
                        $connection = $database;
                        $command = $connection->createCommand()->batchInsert('shbb_park_real_time_data', $sql_unit, $Sql);
                        $command->execute();
                    } catch (Exception $e) {//sql出现错误,返回SQL执行错误语句
                        $transaction->rollback();//回退所有的sql
                        return $this->returnjsontest('-1', self::getErrorCode('-1'), $e->getMessage());
                    }
                    $transaction->commit();//提交数据库
                } else {//格式不正确，数据不在数组里
                    return $this->returnjsontest('4003', self::getErrorCode('4003'));

                }
                return $this->returnjsontest('200', self::getErrorCode('200'));

            }
        }
    }
    public function getdatabase(){
        return Yii::$app->db;
        //return Yii::$app->db_v_shbb;
    }
    //actionGetjsontest函数中返回Json数据
    public function returnjsontest($error = '0', $status, $errormsg = null)
    {
        if (empty($error) || $error == '') {
            $error = '0';
        }
        if (empty($errormsg)) {
            return array('error' => $error, 'status' => $status);
        } else {
            return array('error' => $error, 'status' => $status, 'errormsg' => $errormsg);
        }


    }

    /**
     * 暂时不写
     * @return array
     */
    public function actionXmlsample()
    {
        //$data = Yii::$app->request->get();
        $DataSet = ['EquipID' => 1, 'data' => 1.0, 'state' => 'common'];
        $DataSet1 = ['EquipID' => 2, 'data' => 'on', 'state' => 'running'];
        $DataSet2 = ['EquipID' => 3, 'data' => '3', 'state' => 'No response'];
        $search = array('parkID' => '1', 'SendDate' => '2015-1-1', 'DataSet' => [$DataSet, $DataSet1, $DataSet2], 'Language' => 'xml');
//         $search=array();
//         $search[0]=['EquipID'=>1];$search[1]=['EquipID'=>2];
        Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
        //\yii\web\XmlResponseFormatter::$rootTag='asc';
        //直接return 得到就是json
        return $search;
    }

    /**md5 phpmd5test
     * @param string $message
     * @return string
     */
    public function  actionGetmd5($message = 'Hello World! '){
        $request = Yii::$app->request;
        if($request->isPost){
            $message=$request->post("message");
        }
        if(!empty($message)) {
            $result = ma\matest::getmd5($message);
        }
        echo $result;
        //return $this->render('say', ['message' => $result]);
    }

    /**md5 phpbase64test
     * @param string $message
     * @return string
     */
    public function  actionGetbase64($message = 'Hello World! '){
        $request = Yii::$app->request;
        if($request->isPost){
            $message=$request->post("message");
        }
        if(!empty($message)) {
            $result = ma\matest::getbase64($message);
        }
        echo $result;
        //return $this->render('say', ['message' => $result]);
    }




    /**
     *  AES加密
     *  use yii\base\Security;
     *  use headers when use post
     * @param string $message
     * @param string $key
     */
    public function actionEncodeaesdemo($message = 'Hello World!',
                                        $key='1234567'){
        $request = Yii::$app->request;
        if($request->isPost){
            $headers = $request->headers;
            $message=$headers->get("message");
            $key=$headers->get("key");
        }if(empty($key)){
            $key='1234567';
        }
        $result=ma\MAAES::encrypt_with_base64($message,$key);
//        $result =ma\matest::getbase64($result);
        echo $result;
    }

    /**
     * AES解密
        * use yii\base\Security;
        * use headers when use post
     * @param string $message
        * @param string $key
        */
    public function actionDecodeaesdemo($message = 'SPm21K443p96TS71lEsFTQ==',
                                        $key='1234567'){
        $request = Yii::$app->request;
        if($request->isPost){
            $headers = $request->headers;
            $message=$headers->get('message');
            $key=$headers->get('key');
        }if(empty($key)){
            $key='1234567';
        }

//        $message=ma\matest::getfrombase64($message);
        $result=ma\MAAES::decrypt_with_base64($message,$key);
        echo $result;
    }




}
